package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车
 *
 * 加入购物车
 * 查询购物车
 */
@RestController
@RequestMapping("/api/cart/")
public class CartApiController {


    @Autowired
    private CartInfoService cartInfoService;

    //查询刚刚加入的购物车
    @GetMapping("/getCartInfo/{skuId}/{userId}")
    public CartInfo getCartInfo(@PathVariable(name = "skuId") Long skuId,
                                @PathVariable(name = "userId") String userId){
        return cartInfoService.getCartInfo(skuId,userId);
    }


    //加入购物车
    @GetMapping("addToCart/{skuId}/{skuNum}")
    public CartInfo addToCart(
            @PathVariable(name = "skuId") Long skuId,
            @PathVariable(name = "skuNum") Integer skuNum,
            HttpServletRequest request
            ){
        //真实用户
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //临时用户ID
            userId = AuthContextHolder.getUserTempId(request);
        }
        return cartInfoService.addToCart(skuId,skuNum,userId);
    }
    //去购物车结算  为了查询当前用户的所有购物车
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        //真实用户
        String userId = AuthContextHolder.getUserId(request);
        //临时用户
        String userTempId = AuthContextHolder.getUserTempId(request);
        //合并后集合
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);

        return Result.ok(cartInfoList);
    }

    //更新选中状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(
            @PathVariable(name = "skuId") Long skuId,
            @PathVariable(name = "isChecked") Integer isChecked
    ){
        cartInfoService.checkCart(skuId,isChecked);
        return Result.ok();
    }
    //删除
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart( @PathVariable(name = "skuId") Long skuId){
        cartInfoService.deleteCart(skuId);
        return Result.ok();
    }

    //获取 购物车集合（选中的）
    @GetMapping("/findCartInfoListByChecked")
    public List<CartInfo> findCartInfoListByChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.findCartInfoListByChecked(userId);
    }
}
